package com.scau.phr.business.message.controller;

import com.scau.phr.business.auth.domain.Session;
import com.scau.phr.business.auth.service.SimpleSessionServiceImpl;
import com.scau.phr.business.message.service.MessageService;
import com.scau.phr.common.exceptions.ErrorCode;
import com.scau.phr.common.exceptions.ServiceException;
import com.scau.phr.domain.entity.PhrMessage;
import com.scau.phr.domain.mapper.PhrMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * PHR站内信息表
 * @author yuzhiyi
 * @date 2018/8/13 11:00
 */
@RestController
@RequestMapping("/message")
public class MessageController {

	@Autowired
	SimpleSessionServiceImpl sessionService;

	@Autowired
	MessageService messageService;

	/**
	 * 获取当前用户的所有消息
	 */
	@RequestMapping("/all")
	public Object getAllMessage(){
		String userTel = getCurrentUserTel();
		return messageService.getAllMessage(userTel);
	}

	/**
	 * 获取 now() => send_time >= timestamp的当前用户所有消息
	 * 然后返回now()的时间戳作为前端的下一次请求时间
	 * @return
	 */
	@RequestMapping("/more")
	public Object getMoreMessage(@RequestParam("date") String time){
		String userTel = getCurrentUserTel();
		LocalDateTime dateTime = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME);
		return messageService.getMessageAfterSendTime(userTel,dateTime);
	}

	@RequestMapping("/mark")
	public Object markMessageReaded(@RequestParam("messageId") Long messageId){
		messageService.markMessageReaded(messageId);
		return true;
	}


	/**
	 *	添加新消息(该接口仅用作测试)
	 */
	@RequestMapping("add")
	public Object pushNewMessage(@RequestParam("sender") String sender
								,@RequestParam("receiver") String receiver
								,@RequestParam("content") String content){
		return messageService.addMessage(sender,receiver,content,"系统消息",LocalDateTime.now());
	}

	/**
	 * 获取当前用户的手机号
	 */
	private String getCurrentUserTel(){
		Session session = sessionService.getCurrentSession();
		if (session == null){
			throw new ServiceException(ErrorCode.AUTH_ERROR,"Token不存在或者过期");
		}
		return session.getUsername();
	}


}
